package com.gcloud.mesh.monitor.timer;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gcloud.mesh.asset.dao.IaasDao;
import com.gcloud.mesh.asset.enums.DeviceType;
import com.gcloud.mesh.header.vo.asset.DeviceItemVo;
import com.gcloud.mesh.header.vo.supplier.YingZeSupervisionSystemVo;
import com.gcloud.mesh.monitor.dao.StatisticsDao;
import com.gcloud.mesh.monitor.entity.StatisticsEntity;
import com.gcloud.mesh.supplier.dao.SupplierDao;
import com.gcloud.mesh.supplier.entity.SupplierEntity;
import com.gcloud.mesh.utils.SupplierSystemTypeUtil;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class EnvironmentTimer {

	@Autowired
	StatisticsDao statisticsDao;

	@Autowired
	private IaasDao iaasDao;
	
	@Autowired
	private SupplierDao supplierDao;

	private static final String TYPE = "supervision_system_yingze";

	private static Map<String, String> metrics = new HashMap<String, String>();

	private Map<String, String> values = new HashMap<String, String>();

	private static Map<String, String> devices = new HashMap<String, String>();

	static {
		metrics.put("51", "environment.air_out_temperature"); // 温湿度_温度
		metrics.put("52", "environment.air_out_humidity"); // 温湿度_湿度
		// metrics.put("53"); // 温湿度_通讯状态
		// metrics.put("54"); // 漏水报警
		// metrics.put("55"); // 烟感报警
		metrics.put("71", "environment.ups_in_voltage"); // UPS_输入电压
		metrics.put("72", "environment.ups_in_frequency"); // UPS_输入频率
		metrics.put("73", "environment.ups_out_voltage"); // UPS_输出电压
		metrics.put("74", "environment.ups_out_frequency"); // UPS_输出频率
		metrics.put("75", "environment.ups_battery_voltage"); // UPS_电池电压
		// metrics.put("76"); // UPS_电池后备时间
		metrics.put("77", "environment.ups_temperature"); // UPS_电池温度
		metrics.put("78", "environment.ups_out_load"); // UPS_输出负载百分比
		metrics.put("79", "environment.ups_power"); // UPS_输出有功功率
		// metrics.put("81"); // UPS_通讯状态
	}

	@Scheduled(fixedDelay = 1000 * 60 * 4)
	public void work() {

		List<SupplierEntity> suppliers = supplierDao.findAll().stream().filter(s -> TYPE.equals(s.getType()))
				.collect(Collectors.toList());
		for (SupplierEntity supplier : suppliers) {

			YingZeSupervisionSystemVo obj = (YingZeSupervisionSystemVo) SupplierSystemTypeUtil
					.getByName(supplier.getType(), supplier.getConfig());

			String hostIp = obj.getHostIp();
			String port = obj.getPort();

			this.getDevices(hostIp, port);
			this.getData(hostIp, port);

			if (values != null && values.size() > 0) {
				for (String key : metrics.keySet()) {
					StatisticsEntity entity = new StatisticsEntity();
					entity.setId(UUID.randomUUID().toString());
					entity.setMeter(metrics.get(key));

					entity.setTimestamp(new Date());
					entity.setValue(Double.valueOf(values.get(key)));

					if (entity.getMeter().contains("air")) {
						List<DeviceItemVo> items = iaasDao.listDevice(supplier.getDatacenterId(), DeviceType.AIR_CONDITION.getNo());
						for (DeviceItemVo item : items){
							if(item.getDeviceId().equals(devices.get("air"))){
								entity.setResourceId(item.getId());
							}
						}
					} else if (entity.getMeter().contains("ups")) {
						List<DeviceItemVo> items = iaasDao.listDevice(supplier.getDatacenterId(), DeviceType.UPS.getNo());
						for (DeviceItemVo item : items){
							if(item.getDeviceId().equals(devices.get("ups"))){
								entity.setResourceId(item.getId());
							}
						}
					}
					statisticsDao.save(entity);
				}
			}else {
				log.debug("[EnvironmentTimer] 未采集到动环数据!");
			}
		}
	}

	private void getDevices(String hostIp, String port) {
		String url = "http://" + hostIp + ":" + port + "/device/list";
		RestTemplate restTemplate = new RestTemplate();
		String res = restTemplate.getForEntity(url, String.class).getBody();
		JSONArray jsonArray = JSONArray.parseArray(res);
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject json = jsonArray.getJSONObject(i);
			if (json.getString("name").equals("温湿度")) {
				devices.put("air", json.getString("DeviceID"));
			} else if (json.getString("name").equals("UPS")) {
				devices.put("ups", json.getString("DeviceID"));
			}
		}
	}

	private void getData(String hostIp, String port) {

		String url = "http://" + hostIp + ":" + port + "/tag/value/list";
		RestTemplate restTemplate = new RestTemplate();
		String res = restTemplate.getForEntity(url, String.class).getBody();
		JSONArray jsonArray = JSONArray.parseArray(res);
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject json = jsonArray.getJSONObject(i);
			values.put(json.getString("tid"), json.getString("val"));
		}
	}
}
